package redfin_automation_project1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
public class DDF3 {
	static WebDriver myD;
	static String vURL, vCity, vZip, vminPrice, vmaxPrice, vminBed, vminBath, vhomeAddress;
	static String oTotResults, vTotResults;
	int xRows, xCols;
	String[][] vTD;
	
	@Before
	public void mainBefore() throws Exception{
		// Define your webdriver and initialize it
		vTD = readXL("C:\\CoreJava\\WebDriver\\Tutorials\\Test Data.xls", "Sheet1");				
	}

	@Test
	public void mainTest() throws Exception{
		String vResult1, vResult2, vResult3, vError, vScreenShot;
		// Get each set of Test Data
		for (int vRow=1;vRow<xRows;vRow++) {
			if(vTD[vRow][13].equals("Y")){ 
				try {
						//myD = new FirefoxDriver();
						if(vTD[vRow][14].equals("FF")){ 
							myD = new FirefoxDriver();
						}
						if(vTD[vRow][14].equals("IE")){ 
							myD = new InternetExplorerDriver();							
						}
						if(vTD[vRow][14].equals("HTML")){ 
							myD = new HtmlUnitDriver();							
						}
						if(vTD[vRow][14].equals("Chrome")){ 
							myD = new ChromeDriver();							
						}
						myD.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
						System.out.println("Executing test for test data : " +vTD[vRow][0]);
						
						// Initialive the variables
						vURL = vTD[vRow][1];
						vCity = vTD[vRow][2];
						vZip = vTD[vRow][3];
						vminPrice = vTD[vRow][4];
						vmaxPrice = vTD[vRow][5];
						vminBed = vTD[vRow][6]; 
						vminBath = vTD[vRow][7];
						vhomeAddress = vTD[vRow][8];
						vTotResults = vTD[vRow][9];
					// Get data from each row in the excel sheet
			
					// Execute the Test Case for each set of Test Data
					// TC001 - Search for Homes
						myD.navigate().to(vURL);
						myD.findElement(By.xpath("//input[@id='searchLocation']")).clear();
						myD.findElement(By.xpath("//input[@id='searchLocation']")).sendKeys(vZip);
						Select myO = new Select(myD.findElement(By.xpath("//select[@id='min_price']")));
						myO.selectByVisibleText(vminPrice);
						//myD.findElement(By.xpath("//select[@id='max_price']")).sendKeys(vmaxPrice);
						//myD.findElement(By.xpath("//select[@id='num_beds']")).sendKeys(vminBed);
						//myD.findElement(By.xpath("//select[@id='num_baths']")).sendKeys(vminBath);
						myD.findElement(By.xpath("//div[@id='runSearchButton']")).click();
						Thread.sleep(10000);
			
					// Verify Total Results
						oTotResults = myD.findElement(By.xpath("//span[@dojoattachpoint='numResultsNode']")).getText();
						
						System.out.println("Results on AUT: " + oTotResults);
						System.out.println("Results Expected: " + vTotResults);
						
						if( oTotResults.equals(vTotResults)) {
							System.out.println("Pass TC001.1");
							vResult1 = "Pass";
						} else {
							System.out.println("Fail TC001.1");
							vResult1 = "Fail";
						}
			
					// Verify Zip code in edit field
						System.out.println("Zip code is " + myD.findElement(By.xpath("//input[@id='search_location']")).getAttribute("value"));
						if (myD.findElement(By.xpath("//input[@id='search_location']")).getAttribute("value").equals(vZip)) {
							System.out.println("Pass TC001.2");
							vResult2 = "Pass";
						} else {
							System.out.println("Pass TC001.2");
							vResult2 = "Fail";
						}
						
					// Verify the min amount in the drop down field.
						
						String vT1 = vminPrice; //convert $250,000 into $250K
						vT1 = vT1.substring(1);
						String[] vTA = vT1.split(",");
						vT1 = "";
						for (int i=0;i<vTA.length;i++){
							vT1 = vT1 + vTA[i];
						}
						//vT1 = vTA[0] + vTA[1] ;
						long vT2 = Long.parseLong(vT1)/1000;
						String vT3 = "$" + vT2 + "K";
						System.out.println("vminPrice : " +vT3);
						
				
						if (myD.findElement(By.xpath("//select[@id='min_price']")).getAttribute("value").equals(vT3)) {
							System.out.println("Pass TC001.3");
							vResult3 = "Pass";
						} else {
							System.out.println("Pass TC001.3");
							vResult3 = "Fail";
						}
						
						
						// Get results back from the app
			
						if (vResult1.equals("Pass") && vResult2.equals("Pass") && vResult3.equals("Pass")) {
							vTD[vRow][10] = "Pass";
							vTD[vRow][11] = "Pass";
							vTD[vRow][12] = "Pass";
						} else {
							vTD[vRow][10] = "Fail";
							File scrFile = ((TakesScreenshot)myD).getScreenshotAs(OutputType.FILE);
							FileUtils.copyFile(scrFile, new File("c:\\CoreJava\\screenshot-"+vTD[vRow][0] + ".png"));
							vTD[vRow][11] = "TC001.1 is a " + vResult1 + " .TC002 is a " + vResult2 + " . TC003 is a " + vResult3;
							vTD[vRow][12] = "c:\\CoreJava\\screenshot-"+vTD[vRow][0] + ".png";
						}
						myD.quit();
					} catch (Exception e) {
							System.out.println("Error occured on Test Data: " + vTD[vRow][0]);
							vTD[vRow][10] = "Error";
							vTD[vRow][11] = "Due to " + e;
							vTD[vRow][12] = "Error";
					}
				} else {
						vTD[vRow][10] = "Skipped";
						vTD[vRow][11] = "Skipped";
						vTD[vRow][12] = "Skipped";
				}
			} 
		
	}
	
	@After
	public void mainAfter() throws Exception {
		// Write back into the excel
		writeXL("C:\\CoreJava\\WebDriver\\Tutorials\\Test Result.xls", "Sheet1", vTD);	
		
	}
	// Method to read XL
	
	public String[][] readXL(String sPath, String iSheet) throws Exception{
			String[][] xData;   

			File myxl = new File(sPath);                                
			FileInputStream myStream = new FileInputStream(myxl);                                
			HSSFWorkbook myWB = new HSSFWorkbook(myStream);                                
			HSSFSheet mySheet = myWB.getSheet(iSheet);                                 
			xRows = mySheet.getLastRowNum()+1;                                
			xCols = mySheet.getRow(0).getLastCellNum();                                
			xData = new String[xRows][xCols];        
			for (int i = 0; i < xRows; i++) {                           
					HSSFRow row = mySheet.getRow(i);
					for (int j = 0; j < xCols; j++) {                               
						HSSFCell cell = row.getCell(j);                               
						String value = cellToString(cell);                               
						xData[i][j] = value;                               
						}        
					}                                      
			return xData;
		}
		
		// Method to write into an XL
		public void writeXL(String sPath, String iSheet, String[][] xData) throws Exception{

	    	File outFile = new File(sPath);
	        HSSFWorkbook wb = new HSSFWorkbook();
	        HSSFSheet osheet = wb.createSheet(iSheet);
	        int xR_TS = xData.length;
	        int xC_TS = xData[0].length;
	    	for (int myrow = 0; myrow < xR_TS; myrow++) {
		        HSSFRow row = osheet.createRow(myrow);
		        for (int mycol = 0; mycol < xC_TS; mycol++) {
		        	HSSFCell cell = row.createCell(mycol);
		        	cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		        	cell.setCellValue(xData[myrow][mycol]);
		        }
		        FileOutputStream fOut = new FileOutputStream(outFile);
		        wb.write(fOut);
		        fOut.flush();
		        fOut.close();
	    	}
		}
		
		//Change cell type
		public static String cellToString(HSSFCell cell) { 
			// This function will convert an object of type excel cell to a string value
			int type = cell.getCellType();                        
			Object result;                        
			switch (type) {                            
				case HSSFCell.CELL_TYPE_NUMERIC: //0                                
					result = cell.getNumericCellValue();                                
					break;                            
				case HSSFCell.CELL_TYPE_STRING: //1                                
					result = cell.getStringCellValue();                                
					break;                            
				case HSSFCell.CELL_TYPE_FORMULA: //2                                
					throw new RuntimeException("We can't evaluate formulas in Java");  
				case HSSFCell.CELL_TYPE_BLANK: //3                                
					result = "%";                                
					break;                            
				case HSSFCell.CELL_TYPE_BOOLEAN: //4     
					result = cell.getBooleanCellValue();       
					break;                            
				case HSSFCell.CELL_TYPE_ERROR: //5       
					throw new RuntimeException ("This cell has an error");    
				default:                  
					throw new RuntimeException("We don't support this cell type: " + type); 
					}                        
			return result.toString();      
			}
		
	
}
